package com.example.common.sdk.widget

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.DialogInterface.OnShowListener
import android.view.View
import com.example.common.sdk.R

abstract class CommonDialog(context: Context) {
    private val dialog: Dialog
    abstract fun contentView(): View
    init {
        dialog = Dialog(context, R.style.library_dialog_style)
        dialog.setContentView(contentView())

    }

    private fun init(){
    }

    fun setCancelable(cancel: Boolean): CommonDialog {
        dialog.setCancelable(cancel)
        dialog.setCanceledOnTouchOutside(cancel)
        return this
    }

    fun show() {
        if (!isShowing) {
            dialog.show()
        }
    }

    val isShowing: Boolean
        get() = dialog.isShowing

    fun setGravity(gravity: Int): CommonDialog {
        if (dialog.window != null) {
            dialog.window!!.setGravity(gravity)
        }
        return this
    }

    fun setWindowSize(width: Int, height: Int): CommonDialog {
        val window = dialog.window
        if (window != null) {
            val lp = window.attributes
            lp.width = width
            lp.height = height
            window.decorView.setPadding(0, 0, 0, 0)
            window.attributes = lp
        }
        return this
    }

    fun setWindowSize(width: Int, height: Int, x: Int, y: Int): CommonDialog {
        val window = dialog.window
        if (window != null) {
            val lp = window.attributes
            lp.width = width
            lp.height = height
            lp.x = x
            lp.y = y
            window.decorView.setPadding(0, 0, 0, 0)
            window.attributes = lp
        }
        return this
    }

    fun setDimAmount(amount: Float): CommonDialog {
        if (dialog.window != null) {
            dialog.window!!.setDimAmount(amount)
        }
        return this
    }

    fun dismiss() {
        if (isShowing) {
            dialog.dismiss()
        }
    }

    fun setOnDismissListener(onDismissListener: DialogInterface.OnDismissListener): CommonDialog {
        dialog.setOnDismissListener(onDismissListener)
        return this
    }

    fun setOnShowListener(onShowListener: OnShowListener): CommonDialog {
        dialog.setOnShowListener(onShowListener)
        return this
    }


}